package com.gitease.quickhub.service.impl;

import com.gitease.quickhub.model.User;
import com.gitease.quickhub.repository.UserRepository;
import com.gitease.quickhub.service.GiteeApiService;
import com.gitease.quickhub.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final GiteeApiService giteeApiService;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, GiteeApiService giteeApiService) {
        this.userRepository = userRepository;
        this.giteeApiService = giteeApiService;
    }

    @Override
    public User getUserByLogin(String login) {
        return userRepository.findByLogin(login).orElse(null);
    }

    @Override
    public User saveUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public User getUserByAccessToken(String accessToken) {
        User giteeUser = giteeApiService.getUserInfo(accessToken);
        Optional<User> existingUser = userRepository.findById(giteeUser.getId());
        
        if (existingUser.isPresent()) {
            User user = existingUser.get();
            user.setAccessToken(accessToken);
            user.setName(giteeUser.getName());
            user.setAvatarUrl(giteeUser.getAvatarUrl());
            user.setEmail(giteeUser.getEmail());
            user.setBio(giteeUser.getBio());
            return userRepository.save(user);
        } else {
            giteeUser.setAccessToken(accessToken);
            return userRepository.save(giteeUser);
        }
    }

    @Override
    public User authenticateUser(String code) {
        String accessToken = giteeApiService.getAccessToken(code);
        return getUserByAccessToken(accessToken);
    }

    @Override
    public User refreshUserToken(String refreshToken) {
        String newAccessToken = giteeApiService.refreshAccessToken(refreshToken);
        // We need to find the user by refresh token first
        // This is a simplified implementation
        // In a real application, you would store the refresh token with the user
        // and look up the user by refresh token
        User giteeUser = giteeApiService.getUserInfo(newAccessToken);
        Optional<User> existingUser = userRepository.findById(giteeUser.getId());
        
        if (existingUser.isPresent()) {
            User user = existingUser.get();
            user.setAccessToken(newAccessToken);
            user.setRefreshToken(refreshToken);
            user.setTokenExpiresAt(Instant.now().plusSeconds(7200).getEpochSecond()); // Assuming 2 hour expiry
            return userRepository.save(user);
        }
        
        return null;
    }
}